const ExcelJS = require('exceljs')
const fs = require('fs')
require('./db');
let Models = require('./db/model');

async function query(Models) {
  let arr = await Models.find()
  let obj = {}
  arr.forEach(item => {
    let list = item.list
    if (list) {
      for (let stock in list) {
        if (!obj[stock]) {
          obj[stock] = 0
        }
        obj[stock] += list[stock]*item.size
        // obj[stock] += list[stock]
      }
    }
  })

  let newArr = Object.keys(obj)
    .map(key => ({ name: key, value: obj[key] }))
    .sort((a, b) => {
      return b.value - a.value
    })
  // console.log(newArr.slice())
  // exportExcel(newArr)
  return newArr
}


async function duibi() {
  console.time("query");
  let [newArr, oldArr] = await Promise.all([query(Models.jjModel), query(Models.oldjjModel)])
  console.timeEnd("query");
  let oldObj = {}  
  oldArr.forEach((item, index) => {
    oldObj[item.name] = index
  })
  newArr.forEach((item, index)=>{
    // item.seq = oldObj[item.name] - index
    item.seq = oldObj[item.name] ? (oldObj[item.name] - index) : 'new'
  })
  exportExcel(newArr, '排序对比')
}



async function exportExcel(data, name) {
  const workbook = new ExcelJS.Workbook();
  const worksheet = workbook.addWorksheet('My Sheet');
  worksheet.columns = [
    { header: 'name', key: 'name', width: 20 },
    { header: '值', key: 'value', width: 20 },
    { header: '之前排序', key: 'seq', width: 20 },
  ];
  data.forEach(item => {
    worksheet.addRow(item);
  })
  const buffer = await workbook.xlsx.writeBuffer();
  let ws = fs.createWriteStream(name+'.xlsx')
  ws.write(buffer, (err)=>{
    console.log(err)
    if(!err) {
      console.log('写入成功')
      ws.end()
    }
  })
}

// query()
duibi()